# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 聚合管道操作之out用法.py
# @Author: dongguangwen
# @Date  : 2025-06-15 17:49
from pymongo import MongoClient

# 连接 MongoDB
client = MongoClient("mongodb://root:root123@192.168.1.119:27017/")
db = client["learning_mongodb"]
collection = db["users"]

# 插入测试数据（如果你没有数据）
test_users = [
    {"name": "Alice", "address": {"city": "Shanghai2"}, "is_active": True, "age": 28},
    {"name": "Bob", "address": {"city": "Beijing2"}, "is_active": True, "age": 32},
    {"name": "Charlie", "address": {"city": "Shanghai2"}, "is_active": False, "age": 25},
    {"name": "David", "address": {"city": "Guangzhou2"}, "is_active": True, "age": 40},
    {"name": "Eve", "address": {"city": "Beijing2"}, "is_active": True, "age": 22},
]
collection.insert_many(test_users)
print("已插入测试数据")

# 定义聚合管道
pipeline = [
    {"$match": {"is_active": True}},  # 筛选活跃用户
    {
        "$group": {
            "_id": "$address.city",
            "user_count": {"$sum": 1}
        }
    },
    {"$sort": {"user_count": -1}},
    {
        "$out": "active_users_by_city"  # 将结果写入新集合（若存在则覆盖）
    }
]

# 执行聚合
result = list(collection.aggregate(pipeline))
print(result)

# 查询写入的结果
result_collection = db["active_users_by_city"]
print("\n写入结果（使用 $out）：")
for doc in result_collection.find():
    print(doc)

"""
已插入测试数据
[]

写入结果（使用 $out）：
{'_id': 'Beijing', 'user_count': 2}
{'_id': 'Shanghai', 'user_count': 1}
{'_id': 'Guangzhou', 'user_count': 1}
"""